<?php

/**
 * SmartPHP framework
 *
 * @name SmartPHP framework
 * @package SmartPHP
 * @author 费尔 <admin@smartphp.cn>
 * @version 1.0 Beta
 * @link http://www.smartphp.cn
 * @copyright smartphp.cn
 * @license <a href="http://www.smartphp.cn">smartphp</a>
 */

namespace Driver\Log;

/**
 * 本地化日志
 */
class File {

    protected $config = [
        'timeformat' => ' c ',
        'filesize' => 2097152,
        'path' => LOG_PATH,
    ];

    /**
     * 日志写入接口
     * @access public
     * @param array $log 日志信息
     * @return bool
     */
    public function save(array $log = []) {
        $now = date($this->config['timeformat']);
        $destination = $this->config['path'] . date('y_m_d') . '.log';
        !is_dir($this->config['path']) && \Base\File::mkDir($this->config['path'], 0755, true);
        if (is_file($destination) && floor($this->config['filesize']) <= filesize($destination)) {
            rename($destination, dirname($destination) . DS . $_SERVER['REQUEST_TIME'] . '-' . basename($destination));
        }
        // 获取基本信息
        if (isset($_SERVER['HTTP_HOST'])) {
            $current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        } else {
            $current_uri = "cmd:" . implode(' ', $_SERVER['argv']);
        }
        $runtime = \Base\App::getUsageTime();
        $reqs = number_format(1 / number_format($runtime, 8), 2);
        $time_str = ' [运行时间：' . $runtime . 's][吞吐率：' . $reqs . 'req/s]';
        $memory_str = ' [内存消耗：' . \Base\App::getUsageMemory() . ']';
        $file_load = ' [文件加载：' . count(get_included_files()) . ']';

        $info = '[ log ] ' . $current_uri . $time_str . $memory_str . $file_load . "\r\n";
        $info .= implode("\r\n", $log);

        $server = $_SERVER['SERVER_ADDR'] ?? '0.0.0.0';
        $remote = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
        $method = $_SERVER['REQUEST_METHOD'] ?? 'CLI';
        $uri = $_SERVER['REQUEST_URI'] ?? '';
        return error_log("[{$now}] {$server} {$remote} {$method} {$uri}\r\n{$info}\r\n", 3, $destination);
    }

}
